﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Gencode.PrsCommon.Data.Plan;

namespace Personalplaner.Gui.Mask
{
    [ToolboxItem(false)]
	public partial class PlanLayout : UserControl, Gencode.Gengui.Forms.IDialogControl
	{
		DataView m_schemagrid;
		private int PlanID;

		public PlanLayout(int planid)
		{
			InitializeComponent();

			PlanID = planid;
			InitGrid(planid);
		}

		private void InitGrid(int planid)
		{
			m_schemagrid = PlanData.GetPlanSchema(PlanData.GetPlanSchemaID(planid));
            GridLayout.AutoGenerateColumns = false;
			GridLayout.DataSource = m_schemagrid;

            GridLayout.Columns["position"].DataPropertyName = "prsschemaid";
            GridLayout.Columns["prsid"].DataPropertyName = "prsid";
            GridLayout.Columns["vorname"].DataPropertyName = "vorname";
            GridLayout.Columns["nachname"].DataPropertyName = "nachname";
            GridLayout.Columns["abteilung"].DataPropertyName = "abteilungname";
		}

        private void GridLayout_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //keine abteilungen verschieben
            if (int.Parse(m_schemagrid[e.RowIndex].Row["prsid"].ToString()) != 0)
            {
                DataRow row = m_schemagrid.Table.NewRow();
                object[] arr = m_schemagrid.Table.Rows[e.RowIndex].ItemArray;
                row.ItemArray = arr;

                switch (e.ColumnIndex)
                {
                    case 0: //Up
                        if (e.RowIndex > 0 &&
                            int.Parse(m_schemagrid[e.RowIndex].Row["abteilungid"].ToString()) == int.Parse(m_schemagrid[e.RowIndex - 1].Row["abteilungid"].ToString()) &&
                            int.Parse(m_schemagrid[e.RowIndex - 1].Row["prsid"].ToString()) != 0)
                        {
                            m_schemagrid.Table.Rows.RemoveAt(e.RowIndex);
                            m_schemagrid.Table.Rows.InsertAt(row, e.RowIndex - 1);
							GridLayout.Rows[e.RowIndex - 1].Selected = true;
                        }
                        break;
                    case 1: //Down
                        if (e.RowIndex < GridLayout.Rows.Count - 1 &&
                            int.Parse(m_schemagrid[e.RowIndex].Row["abteilungid"].ToString()) == int.Parse(m_schemagrid[e.RowIndex + 1].Row["abteilungid"].ToString()) &&
                            int.Parse(m_schemagrid[e.RowIndex + 1].Row["prsid"].ToString()) != 0)
                        {
                            m_schemagrid.Table.Rows.RemoveAt(e.RowIndex);
                            m_schemagrid.Table.Rows.InsertAt(row, e.RowIndex + 1);
							GridLayout.Rows[e.RowIndex + 1].Selected = true;
                        }
                        break;
                }
            }
        }

        private void PlanLayout_Load(object sender, EventArgs e)
        {
            //set colors
            for (int i = 0; i < m_schemagrid.Table.Rows.Count; i++)
            {
                if (int.Parse(m_schemagrid[i].Row["rgb"].ToString()) != -1 &&
                    int.Parse(m_schemagrid[i].Row["rgb"].ToString()) != 0)
                {
                    GridLayout.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(int.Parse(m_schemagrid[i].Row["rgb"].ToString()));
                }

				if (int.Parse(m_schemagrid[i].Row["prsid"].ToString()) == 0)
				{
					((DataGridViewImageCell)GridLayout.Rows[i].Cells[0]).Value = Personalplaner.Properties.Resources.Navigation_transparent;
					((DataGridViewImageCell)GridLayout.Rows[i].Cells[1]).Value = Personalplaner.Properties.Resources.Navigation_transparent;
				}
            }
        }


		#region IDialogControl Members

		public bool OKClicked()
		{
            if (m_schemagrid.Count > 0)
            {
				Gencode.Common.ActionLogger.Logger.LoggMessage(Gencode.Common.ActionLogger.MessageType.USER_EVENT, "Update schema in plan " + PlanID + " from PlanLayout(in plan)");
                int schemaid = int.Parse(m_schemagrid[0].Row["schemaid"].ToString());
                PlanData.DeleteRowsFromSchema(schemaid);
                for (int i = 1; i <= m_schemagrid.Count; i++)
                {
                    PlanData.SaveSchemaRow(schemaid, i, int.Parse(m_schemagrid[i - 1].Row["prsid"].ToString()),
                        int.Parse(m_schemagrid[i - 1].Row["abteilungid"].ToString()),
                        int.Parse(m_schemagrid[i - 1].Row["rgb"].ToString()));
                }
            }
            m_schemagrid.Dispose();
			return true;
		}

		public bool CancleClicked()
		{
			return true;
		}

		#endregion

        private Rectangle dragBoxFromMouseDown;
        private int rowIndexFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;
        
        private void GridLayout_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                // If the mouse moves outside the rectangle, start the drag.
                if (dragBoxFromMouseDown != Rectangle.Empty &&
                    !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {
                    // Proceed with the drag and drop, passing in the list item. 
                    DragDropEffects dropEffect = GridLayout.DoDragDrop(
                      GridLayout.Rows[rowIndexFromMouseDown], DragDropEffects.Move);

                }
            }
        }

        private void GridLayout_MouseDown(object sender, MouseEventArgs e)
        {
            // Get the index of the item the mouse is below.
            rowIndexFromMouseDown = GridLayout.HitTest(e.X, e.Y).RowIndex;

            if (rowIndexFromMouseDown != -1)
            {
                // Remember the point where the mouse down occurred. 
                // The DragSize indicates the size that the mouse can move 
                // before a drag event should be started. 
                Size dragSize = SystemInformation.DragSize;

                // Create a rectangle using the DragSize, with the mouse position being
                // at the center of the rectangle.
                dragBoxFromMouseDown = new Rectangle(
                  new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
            }
            else
                // Reset the rectangle if the mouse is not over an item in the ListBox.
                dragBoxFromMouseDown = Rectangle.Empty;
        }

        private void GridLayout_DragDrop(object sender, DragEventArgs e)
        {
            // The mouse locations are relative to the screen, so they must be 
            // converted to client coordinates.
            Point clientPoint = GridLayout.PointToClient(new Point(e.X, e.Y));

            // Get the row index of the item the mouse is below. 
            rowIndexOfItemUnderMouseToDrop =
              GridLayout.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

            // If the drag operation was a move then remove and insert the row.
            if (e.Effect == DragDropEffects.Move)
            {
                //DataGridViewRow rowToMove = e.Data.GetData(
                //  typeof(DataGridViewRow)) as DataGridViewRow;
                //GridLayout.Rows.RemoveAt(rowIndexFromMouseDown);
                //GridLayout.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

                DataRow row = m_schemagrid.Table.NewRow();
                row[0] = m_schemagrid[rowIndexFromMouseDown][0];
                row[1] = m_schemagrid[rowIndexFromMouseDown][1];
                row[2] = m_schemagrid[rowIndexFromMouseDown][2];
                row[3] = m_schemagrid[rowIndexFromMouseDown][3];
                row[4] = m_schemagrid[rowIndexFromMouseDown][4];
                row[5] = m_schemagrid[rowIndexFromMouseDown][5];
                row[6] = m_schemagrid[rowIndexFromMouseDown][6];
                row[7] = m_schemagrid[rowIndexFromMouseDown][7];
                row[8] = m_schemagrid[rowIndexFromMouseDown][8];
                m_schemagrid.Table.Rows.RemoveAt(rowIndexFromMouseDown);
                m_schemagrid.Table.Rows.InsertAt(row, rowIndexOfItemUnderMouseToDrop);
                
            }
        }

        private void GridLayout_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }
    }
}
